using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;

namespace WebSMS;

public class RuleDataLinkService : ITransient,ITerRuleDataLinks
{
    public readonly IRepository<RuleDataLinks> _ruleDataLinksRepository;
    public RuleDataLinkService(IRepository<RuleDataLinks> ruleDataLinksRepository)
    {
        _ruleDataLinksRepository = ruleDataLinksRepository;
    }

    public Task<List<RuleDataLinks>> GetRuleDataLinksAsync(Guid ruleId)
    {
        List<RuleDataLinks> ruleDataLinksEnumerable =
            _ruleDataLinksRepository.Where(rd => rd.RuleId == ruleId).ToList();
        return Task.FromResult(ruleDataLinksEnumerable);
    }

    public async Task<bool> AddRuleData(bool isUpdate,Guid ruleId,Guid dataId)
    {
        if (isUpdate)
        {
            var queryable = _ruleDataLinksRepository.Where(ud => ud.RuleId == ruleId);
            if (queryable.Count() > 0)
            {
                await _ruleDataLinksRepository.DeleteNowAsync(queryable);
            }
            await _ruleDataLinksRepository.InsertNowAsync(new RuleDataLinks(){Id = Guid.NewGuid(),RuleId = ruleId,DataTypeId = dataId});
            return true;
        }
        await _ruleDataLinksRepository.InsertNowAsync(new RuleDataLinks(){Id = Guid.NewGuid(),RuleId = ruleId,DataTypeId = dataId});
        return true;
        
    }
    
    public async Task<bool> ClearDataLink(Guid ruleId)
    {
        var queryable = _ruleDataLinksRepository.Where(ud => ud.RuleId == ruleId);
        if (queryable.Count() > 0)
        {
            await _ruleDataLinksRepository.DeleteNowAsync(queryable);
            return true;
        }
        else
        {
            return false;
        }
    }
    
}